package com.distribute.framework.core.web;

import com.distribute.framework.core.web.helper.Utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.distribute.framework.core.web.helper.WebHelper;
import com.distribute.framework.core.web.limits.LimitsFilter;
import com.distribute.framework.core.web.servlet.Lazy3qResponseWrapper;
import com.distribute.framework.core.web.session.RedisSessionRequest;
import com.distribute.framework.core.xwork.WebContext;


@SuppressWarnings("unchecked")
public class Lazy3qDispatcher implements Filter
{
	private Boolean limit=false;
	private String capture=null;
	private String FMTag=null;
	
	public void init(FilterConfig arg0) throws ServletException
	{
		try{
			this.limit=Boolean.parseBoolean(arg0.getInitParameter("limit"));
			this.FMTag=arg0.getInitParameter("FMTag");
			this.capture=arg0.getInitParameter("capture");
			String limitKey=arg0.getInitParameter("limitKey");
			if(limitKey!=null && limitKey.equals(""))
				LimitsFilter.setKey(limitKey);
			WebContext.setServletContext(arg0.getServletContext());
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void doFilter(ServletRequest _request, ServletResponse _response,FilterChain filterChain) throws IOException, ServletException
	{
		_request = new RedisSessionRequest((HttpServletRequest) _request);
		
		HttpServletRequest request = (HttpServletRequest) _request;
		HttpServletResponse response=(HttpServletResponse) _response;	
		
		
		//设置Lazy3q上下文
		WebContext.setServletRequest(request);
		WebContext.setServletResponse(response);
		WebContext.setHttpSession(request.getSession());
		
		request.setAttribute("requestStart", new Date());
		
		//权限插件拦截
		if(this.limit)
			LimitsFilter.FilterLimits(request);
		
		//把请求的参数放入request
		Map params = request.getParameterMap();
		Set<String> names = params.keySet();
		for(String name:names)
			request.setAttribute(name,request.getParameter(name));
		
		//放置路径
		String contextPath = request.getContextPath();
		request.setAttribute("contextPath",contextPath);
		String port="";
		if(request.getServerPort()!=80 && request.getServerPort()!=443)
			port=":"+request.getServerPort();
		String basePath = request.getScheme()+"://"+request.getServerName()+port+contextPath+"/";
		request.setAttribute("basePath",basePath);
		String servletPath = request.getServletPath();
		request.setAttribute("servletPath",servletPath);
		String location = request.getScheme()+"://"+request.getServerName()+port+contextPath+servletPath;
		request.setAttribute("location",location);
		request.setAttribute("urlPath",location);
		String namespace = servletPath.substring(0,servletPath.lastIndexOf("/")+1);
		if(namespace.startsWith("/"))namespace = namespace.substring(1);
		request.setAttribute("namespace",namespace);
		
		try{
			String xRequestedWith = Utils.getServletRequest().getHeader("x-requested-with");
			if(xRequestedWith==null){//发送request请求事件,如果ajax请求，放弃统计
				Utils.fire("request");
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
				
		String strUrl=request.getServletPath().toString();
		
		
		//如果设置freemarker之Lazy3q标签
		if(!WebHelper.empty(this.FMTag)){
			try {
				request.setAttribute(this.FMTag,Class.forName("com.distribute.framework.core.web.helper.FremarkerHelper").newInstance());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		String pathName = (String) request.getAttribute("cache.html.path");
		if(!WebHelper.empty(pathName)) {
			pathName=pathName.replaceAll("\\\\", "/").replaceAll("//", "/");
			String filePath=pathName.substring(0,pathName.lastIndexOf("/"));
			if(!new File(filePath).exists())
				new File(filePath).mkdirs();
			OutputStreamWriter osWriter = new java.io.OutputStreamWriter(new FileOutputStream(pathName, false),this.capture);
			Lazy3qResponseWrapper lazyResponse = new Lazy3qResponseWrapper(response,osWriter);
			filterChain.doFilter(request, lazyResponse);
			osWriter.close();
	    } else {
	    	filterChain.doFilter(request, response);
	    }
		
	}

	public void destroy()
	{
		
	}
		
}